export default {
	namespaced: true,
	state: () => {
		return {
			cart: JSON.parse(uni.getStorageSync('cart') || '[]')
		}
	},
	mutations: {
		// 更改所有商品的勾选状态
		updateAllGoodsState(state, newState) {
			state.cart.forEach(item => item.goods_state = newState);
			this.commit('cart_m/saveToStorage');
		},
		removeShop(state, goods_id) {
			state.cart = state.cart.filter(item => item.goods_id !== goods_id);
			this.commit('cart_m/saveToStorage');
		},
		updateGoodsCount(state, goods) {
			const findResult = state.cart.find(item => item.goods_id == goods.goods_id);
			if (findResult) {
				findResult.goods_count = goods.goods_count;
				this.commit('cart_m/saveToStorage');
			}
		},
		addTo(state, goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id);
			if (findResult) {
				findResult.goods_count++;
			} else {
				state.cart.push(goods);
			};
			this.commit('cart_m/saveToStorage')

		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		updateGoodsState(state, goods) {
			const findResult = state.cart.find(item => item.goods_id == goods.goods_id);
			if (findResult) {
				findResult.goods_state = goods.goods_state;
				this.commit('cart_m/saveToStorage');
			}
		}

	},
	actions: {},
	getters: {
		checkedGoodsAmount(state){
			return state.cart.filter(item=>item.goods_state).reduce((total,item)=>{return total+=item.goods_price*item.goods_count},0).toFixed(2)
		},
		// 全选的状态
		checkedCount(state) {
			return state.cart.filter(item => item.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		// 商品的总数量
		total(state) {
			let sum = 0;
			state.cart.forEach(goods => sum += goods.goods_count);
			return sum
		}
	}
}
